var box         = document.getElementById('md5sum');
var spark       = new SparkMD5();
var progress		= document.getElementById('progress');
var md5sumBox		= document.getElementById('md5sum');
var submitBtn		= document.getElementById('submit');
var chunkSize		=	2097152;		// 2M
var process			= $('.process');
var progress		= $('#progress');

	
$(submitBtn).attr('disabled', 'disabled');


var sliceUploader = (file, md5sum) => {
	
	var fileReader		= new FileReader();
  var blobSlice			= File.prototype.mozSlice || File.prototype.webkitSlice || File.prototype.slice;
	var chunks				= Math.ceil(file.size / chunkSize);

	$(submitBtn).removeAttr('disabled');

	$(submitBtn).on('click', () => {

		process.removeClass('hidden');
		$('#pick-file').attr('disabled', 'disabled');
		$(submitBtn).attr('disabled', 'disabled');

		var timer					 = undefined;
		var str			= ($('#file').val()).split('\\');

		var fileInfo = {
			fileName			: str[str.length -1],
			fileSize			:	file.size,
			fileType			: file.type,
			lastModified	: file.lastModified,
			chunks				:	Math.ceil(file.size / chunkSize),
			currentChunk	: 0,
			md5sum				:	md5sum
		};


		var localStorage	= window.localStorage;
		var last					= localStorage.getItem(fileInfo.md5sum);

		//没上传过或者已经清除了浏览器缓存
		if(last == null) {

			var currentChunk	= 0;
			var data					= fileInfo;


			//则分片上传，并记录断点
			fileReader.onload = (e) => {

			var fileData = e.target.result;

			data.currentChunk	=	currentChunk;			
			data.fileData = Base64.encode(fileData);


			$.ajax({
				url					: 'http://localhost:8000/uploader',	
				method			: 'post',
				data				: { data },
				error				: (e) => {
					console.log(e);
				},
				success			:	(data) => {
					data = JSON.parse(data);
					if(currentChunk < chunks) {
						currentChunk = data.currentChunk;
						fileData = null;
						timer = setTimeout( ()=> { loadNext(); }, 2000);
					} else {
						//process.addClass('hidden');
						$('#pick-file').removeAttr('disabled');
					}
				}
			});

			progress.text('上传中：' + currentChunk + '/' + chunks);
		};
  
		function loadNext() {
			if(timer != undefined)
				clearTimeout(timer);
			var start = currentChunk * chunkSize;
			var end		= start + chunkSize >= file.size ? file.size : start + chunkSize;
			fileReader.readAsDataURL(blobSlice.call(file, start, end));
		}
		loadNext();
	}

	
	});


}

//校验文件的md5值，由于分片校验导致程序异步，所以需要传入callback
var MD5sum = function(file, callback)  {

	var fileReader		= new FileReader();
  var blobSlice			= File.prototype.mozSlice || File.prototype.webkitSlice || File.prototype.slice;
	var chunks				= Math.ceil(file.size / chunkSize);
  var currentChunk  = 0;
	var spark					= new SparkMD5();
	var md5sum				= null;


  fileReader.onload = (e) => {
		spark.appendBinary(e.target.result);

		// append binary string
		currentChunk++;

		if (currentChunk < chunks) {
			loadNext();
		} else {
			md5sumBox.innerText = md5sum =   spark.end();
			process.addClass('hidden');
			$('#pick-file').removeAttr('disabled');
			callback(file, md5sum);
		} 
			progress.text('校验中：' + currentChunk + '/' + chunks);
	};
  
	function loadNext() {
		var start = currentChunk * chunkSize;
		var end		= start + chunkSize >= file.size ? file.size : start + chunkSize;
		fileReader.readAsBinaryString(blobSlice.call(file, start, end));
	}

  loadNext();
}

document.getElementById('file').addEventListener('change', () => {

        var file					= document.getElementById('file').files[0];

				$('.process').removeClass('hidden');
				$('#pick-file').attr('disabled', 'disabled');
				window.MD5sum(file, sliceUploader)

});


